package com.ruoyi.common.utils.sign;

import java.security.MessageDigest;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.crypto.hash.Md5Hash;

/**
 * Md5加密方法
 * 
 * @author ruoyi
 */
public class Md5Utils
{
    private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);

    private static byte[] md5(String s)
    {
        MessageDigest algorithm;
        try
        {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        }
        catch (Exception e)
        {
            log.error("MD5 Error...", e);
        }
        return null;
    }

    private static final String toHex(byte hash[])
    {
        if (hash == null)
        {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++)
        {
            if ((hash[i] & 0xff) < 0x10)
            {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s)
    {
        try
        {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        }
        catch (Exception e)
        {
            log.error("not supported charset...{}", e);
            return s;
        }
    }

    public static boolean verify(String text, String md5) throws Exception {
        String md5str = md52salt(text);
        if (md5str.equalsIgnoreCase(md5)) {
            System.out.println("MD5验证通过");
            return true;
        }
        return false;
    }

    public static boolean verify(String password, String md5password,String salt, String username) throws Exception {

        String hex = username + password + salt;
        String md5str = md52salt(hex);
        if (md5str.equalsIgnoreCase(md5password)) {
            System.out.println("MD5验证通过");
            return true;
        }
        return false;
    }

    public static String md52(String text) throws Exception {
        // 加密后的字符串
        String md5str = DigestUtils.md5Hex(text);
        System.out.println("MD52加密后的字符串为:" + md5str + "\t长度：" + md5str.length());
        return md5str;
    }

    //加盐
    public static String md52salt(String text) throws Exception {
        // 加密后的字符串
        String encodedPassword = new Md5Hash(text).toHex();
        System.out.println("MD52加密后的字符串为:" + encodedPassword + "\t长度：" + encodedPassword.length());
        return encodedPassword;
    }


    public static void main(String[] args) throws Exception{
        boolean verify = verify("123", "202cb962ac59075b964b07152d234b70");
        System.out.println(verify);
        String s = md52("123");
        System.out.println(s);

    }
}
